import React, { useEffect, useMemo } from 'react';
import { Form, Button, Row, Col } from 'antd';
import Types from './types';
import { FormRenderProps, FormItemRenderProps } from './type';
import style from './index.less';
// import classNames from 'classnames';

const defaultLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};
const tailLayout = {
  wrapperCol: { offset: 8, span: 16 },
};
/* eslint-disable no-template-curly-in-string */
const validateMessages = {
  required: '请设置${label}',
};

const FormItemRender = ({
  type,
  label,
  name,
  rules = [],
  content,
  enabled,
  defaultText,
  ...res
}: FormItemRenderProps) => {
  const Ele = content || Types[type] || Types.input;
  return (
    <Form.Item label={label} name={name} rules={rules} {...res}>
      {defaultText === undefined ? (
        <Ele
          type={type}
          required={(rules.find((rule) => rule.hasOwnProperty('required')) || {}).required}
          {...res}
        />
      ) : (
        defaultText
      )}
    </Form.Item>
  );
};

// 表单提交按钮
const renderSubmitBtns = (submitBtns = []) => (
  <Form.Item {...tailLayout} className={style.footer}>
    {submitBtns.map((btn) => (
      <Button key={btn.text} {...btn}>
        {btn.text}
      </Button>
    ))}
  </Form.Item>
);

const FormRender = (props: FormRenderProps) => {
  const [defaultForm] = Form.useForm();
  const {
    form = defaultForm,
    formItem,
    layout = defaultLayout,
    onValuesChange,
    defaultData,
    onSubmit,
    submitBtns,
    className,
  } = props;
  // const clsString = classNames(className);

  const onFinish = (values) => {
    if (values) {
      if (onSubmit) {
        onSubmit(values);
      }
    }
  };
  useEffect(() => {
    if (defaultData && Object.keys(defaultData).length > 0) {
      form.setFieldsValue(defaultData);
    } else {
      form.resetFields();
    }
  }, [defaultData]);

  const extraButtonRender = (extraButton) => {
    if (!extraButton || extraButton?.isShow) return '';
    if (extraButton?.renderDom) return extraButton?.renderDom();
    if (Array.isArray(extraButton)) {
      return extraButton?.map((item) => extraButtonRender(item));
    }
    return (
      <Button
        onClick={extraButton?.func}
        className={window.isInCatalog ? style.catalogExtraButton : style.cspExtraButton}
        disabled={extraButton?.disabled}
        style={extraButton?.style}
      >
        {extraButton.text || ''}
      </Button>
    );
  };
  const itemContent = (item) => {
    if (!!item.renderDom)
      return (
        <Row style={{ marginBottom: '12px' }}>
          <Col span={8}>{item?.label}</Col>
          <Col span={8}>{item.renderDom()}</Col>
        </Row>
      );
    return (
      <div key={item.name} className={style.colContent}>
        <FormItemRender key={item.name} {...item} />
        {extraButtonRender(item.extraButton)}
        {item.customeExtraNode && (
          <div className={window.isInCatalog ? style.catalogExtraButton : style.cspExtraButton}>
            {item.customeExtraNode?.()}
          </div>
        )}
      </div>
    );
  };
  return (
    <Form
      form={form}
      onFinish={onFinish}
      onValuesChange={onValuesChange}
      {...layout}
      validateMessages={validateMessages}
      scrollToFirstError
    // className={clsString}
    >
      {formItem.map((item) => {
        if (!!item?.renderDom)
          return (
            <Row style={{ marginBottom: '12px' }}>
              <Col span={6}>{item?.label}</Col>
              <Col span={18}>{item.renderDom()}</Col>
            </Row>
          );
        return item?.Items ? (
          <React.Fragment key={item.title}>
            <div className={`${style.title} dt-custom-theme-border-color`}>{item.title}</div>
            {item.Items.filter((oItems) => !oItems.unenabled).map((oItems) => itemContent(oItems))}
          </React.Fragment>
        ) : (
          !item?.unenabled && itemContent(item)
        );
      })}
      {/* 提交按钮 */}
      {submitBtns && renderSubmitBtns(submitBtns)}
    </Form>
  );
};

export default FormRender;
